package com.inspinia.upms.client.security;

import com.inspinia.upms.common.util.SerializableUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.crazycake.shiro.RedisSessionDAO;
import org.crazycake.shiro.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
 * Created by veblen on 2016/11/17.
 */
public class MyRedisSessionDao extends RedisSessionDAO{

    private static Logger logger = LoggerFactory.getLogger(RedisSessionDAO.class);

    private static final String KEY_PREFIX = "META-INF:session:sessions:";

    /**
     * The Redis key prefix for the sessions
     */
    @Override
    public void update(Session session) throws UnknownSessionException {
        try {
            this.saveSession(session);
        } catch (SerializationException e) {
            e.printStackTrace();
        }
    }

    /**
     * save session
     *
     * @param session
     * @throws UnknownSessionException
     */
    private void saveSession(Session session) throws UnknownSessionException, SerializationException {
        if (session == null || session.getId() == null) {
            logger.error("session or session id is null");
            return;
        }

        byte[] key = getByteKey(session.getId());
        byte[] value = SerializableUtils.serialize(session);

        long timeout = getRedisManager().getExpire() * 1000;
        if (getRedisManager().getExpire() == 0) {
            timeout = -1000;
        }
        //客户端session
        session.setTimeout(timeout);
        getRedisManager().set(key, value,getRedisManager().getExpire());
    }


    /**
     * 获得byte[]型的key
     *
     * @param key
     * @return
     */
    private byte[] getByteKey(Serializable key) {
        String preKey = super.getKeyPrefix() + key;
        return preKey.getBytes();
    }
}
